package com.lanou.musicproject.suspendservice;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import com.lanou.musicproject.R;
import com.lanou.musicproject.bean.MyMusicList;
import com.lanou.musicproject.bean.MySong;
import com.lanou.musicproject.musicservice.MusicInterface;
import com.lanou.musicproject.musicservice.MusicService;
import com.lanou.musicproject.tools.Time;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;


/**
 * Created by  on 15/11/2.
 * 李东
 *
 */
public class FxService extends Service implements View.OnClickListener {
    private static MusicInterface mi;
    private static SeekBar sb;
    private MyServiceConn conn;
    private Intent intent;
    private static ImageView mini_play,mini_next;
    private static TextView playerSongName;
    private static TextView playerSingerName;
    private static CircleImageView player_singer_image;
    private static Context mContext;
    private static TextView start_time,end_time;
    //定义浮动窗口布局
    LinearLayout mFloatLayout;
    WindowManager.LayoutParams wmParams;
    //创建浮动窗口设置布局参数的对象
    WindowManager mWindowManager;
    LinearLayout mFloatView;
    private static final String TAG = "FxService";

    @Override
    public void onCreate() {
        super.onCreate();
        createFloatView();
        initData();
    }

    private void initData() {
        mContext = this;

        start_time = (TextView) mFloatLayout.findViewById(R.id.start_time);
        end_time = (TextView) mFloatLayout.findViewById(R.id.end_time);
        sb = (SeekBar) mFloatLayout.findViewById(R.id.sb);
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                //根据拖动的进度改变音乐播放进度
                int progress = seekBar.getProgress();
                //改变播放进度
                mi.seekTo(progress);

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress,
                                          boolean fromUser) {
            }
        });
        mini_next = (ImageView) mFloatLayout.findViewById(R.id.mini_next);
        mini_play = (ImageView) mFloatLayout.findViewById(R.id.mini_play);
        playerSingerName = (TextView) mFloatLayout.findViewById(R.id.player_singer_name);
        playerSongName = (TextView) mFloatLayout.findViewById(R.id.player_song_name);
        player_singer_image = (CircleImageView) mFloatLayout.findViewById(R.id.player_singer_image);



        intent = new Intent(this, MusicService.class);
        startService(intent);
        conn = new MyServiceConn();
        bindService(intent, conn, BIND_AUTO_CREATE);
        mini_play.setOnClickListener(this);
        mini_next.setOnClickListener(this);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    private void createFloatView(){
        wmParams = new WindowManager.LayoutParams();
        //获取的是WindowMangerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        //设置window type
        wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        //设置图片格式,效果背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        //调整悬浮窗显示停靠位置为左侧置顶
        wmParams.gravity = Gravity.LEFT|Gravity.TOP;
        //以屏幕左上角为原点 ,设置xy初始值,相对于gravity
        wmParams.x = 0;
        wmParams.y = 0;
        //设置悬浮窗口的长宽数据
        wmParams.width =800;
        wmParams.height = 400;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗视图所在布局
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.fxservice_view, null);
        //添加mFloatLayout
        mWindowManager.addView(mFloatLayout, wmParams);
        //浮动窗口按钮
        mFloatView = (LinearLayout) mFloatLayout.findViewById(R.id.move_linear);
        //停止服务
        ImageView abolish_btn = (ImageView) mFloatLayout.findViewById(R.id.abolish_btn);
        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        //设置浮动窗口的触摸移动
        mFloatView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                //getRawX是触摸位置相对于屏幕的坐标，getX是相对于按钮的坐标
                wmParams.x = (int) event.getRawX() - mFloatView.getMeasuredWidth() / 2;

                //减25为状态栏的高度
                wmParams.y = (int) event.getRawY() - mFloatView.getMeasuredHeight() / 2 - 25;

                //刷新
                mWindowManager.updateViewLayout(mFloatLayout, wmParams);
                return false;  //此处必须返回false，否则OnClickListener获取不到监听
            }
        });
        abolish_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                stopFxService();
            }
        });


    }

    public void stopFxService(){
        //uninstallApp("com.phicomm.hu");
        Intent intent = new Intent(FxService.this, FxService.class);
        //终止FxService
        stopService(intent);
//                mFloatView.setVisibility(View.GONE);
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.mini_play) {
            if (mi.getIsPlay()) {
                mi.pause();
            } else if (mi.getDuration() > mi.getProgress()) {
                mi.continuePlay();
            }

        }
        else if (v.getId() == R.id.mini_next) {
            mi.next();
        }
    }
    class MyServiceConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mi = (MusicInterface) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            // TODO Auto-generated method stub
        }

    }

    public static Handler handler = new Handler() {
        public void handleMessage(android.os.Message msgfx) {
            Bundle bundle = msgfx.getData();
            int duration = bundle.getInt("duration");
            int currentPostition = bundle.getInt("currentPosition");
            //刷新进度条的进度
            if(sb!=null){
                sb.setMax(duration);
                sb.setProgress(currentPostition);
                start_time.setText(Time.formatTime((long) currentPostition));
                end_time.setText(Time.formatTime((long) duration));
                init();
            }

        }
    };
    //设置图片样式
    private static void init() {
        if (mi.getIsPlay()) {
            mini_play.setImageResource(R.mipmap.player_btn_pause);
        } else {
            mini_play.setImageResource(R.mipmap.player_btn_play);
        }
        playerSongName.setText(mi.getName());
        playerSingerName.setText(mi.getSinger());
        Picasso.with(mContext).load(mi.getPlayer_Singer_Image()).into(player_singer_image);
    }

    public static void mini_play(ArrayList<MyMusicList> lists, int position) {
        if(mi!= null){
            mi.play(lists, position);
        }
    }

    public static void mini_play(List<MySong> mysong,int position){
        if(mi != null)
            mi.playLocal(mysong,position);
    }
    public void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();
        unbindService(conn);
        if(mFloatLayout != null)
        {
            //移除悬浮窗口
            mWindowManager.removeView(mFloatLayout);
        }
    }
}
